<template>
  <div>
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['设备管理', '设备保养']" currentMenu="保养项目"></crumbs>
    <a-card :bordered="false" style="height: 100%; margin-top: 12px">
      <a-button @click="handleShowFilter" icon="filter"
        >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums }}</span></a-button
      >
      <a-button @click="showColumn" icon="unordered-list" class="btns">设置列</a-button>
      <div class="right-btn">
        <!-- <a-button @click="importFile">导入</a-button>
        <a-button @click="exportFile" class="btns">导出</a-button> -->
        <a-button type="primary" @click="handleAdd"> +新建 </a-button>
      </div>
      <a-table
        row-key="id"
        :key="tableKey"
        size="middle"
        :scroll="{ x: scrollX, y: 'calc(100vh - 366px)' }"
        :hideDefaultSelections="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle: ' ', onChange: onSelectChange }"
        :columns="columns"
        :dataSource="modelList"
        :pagination="false"
        @change="tableChange"
        style="margin-top:24px"
        :components="drag(columns, 'MAINTENANCE_ITEMS')"
      >
        <span slot="actions" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleDelete(record)">删除</a>
        </span>
        <!-- 行信息 -->
        <span slot="projectName" :title="record.projectName" slot-scope="text, record">
          {{  record.projectName  }}
        </span>
        <span slot="maintainStandard" :title="record.maintainStandard" slot-scope="text, record">
          {{  text  }}
        </span>
        <span
          slot="purchaseDate"
          :title="record.purchaseDate ? moment(record.purchaseDate).format('YYYY-MM-DD') : '-'"
          slot-scope="text, record"
        >
          {{ record.purchaseDate ? moment(record.purchaseDate).format('YYYY-MM-DD') : '-' }}
        </span>
        <span slot="remark" :title="record.remark" slot-scope="text, record">
          {{  record.remark  }}
        </span>
        <!-- 输入框搜索 -->
        <div slot="searchInput" slot-scope="{ selectedKeys, confirm, clearFilters, column }" class="searchWorkOreder">
          <a-input
            placeholder="请输入"
            v-model="filterForm[column.dataIndex]"
            style="width: 188px; display: block"
            @pressEnter="handleSearch"
          />
          <a-button
            type="primary"
            style="width: 80px; margin-left: 20px; display: block"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex, clearFilters)"
          >
            搜索
          </a-button>
        </div>
        <a-icon
          slot="searchIcon"
          slot-scope="filtered"
          type="search"
          :style="{ color: filtered ? '#108ee9' : undefined }"
        />
      </a-table>
      <SetColumn
        columnName="设置列"
        ref="SetColumn"
        v-if="showSetColumn"
        @sureBtn="sureBtn"
        @cancelBtn="showSetColumn = false"
      />
    </a-card>
    <!-- 筛选弹窗 -->
    <a-drawer placement="right" width="500" :visible="showFilter" @close="closeFilter">
      <div class="filter-body">
        <div slot="title" class="uni-card filter-tit">
          筛选 <span class="filter-num">{{ filteredNums }}</span>
        </div>
        <div class="uni-card" v-if="filteredNums > 0" style="background: #fff">
          <div v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
            <span class="filter-tag" @click="delFiltered(item.key)">
              <span class="tag-text">{{ `${item.title}：${item.text}` }}</span>
              <a-icon type="close" style="float: right" />
            </span>
          </div>
        </div>
        <div style="overflow-y: scroll; flex: 1; padding: 0">
          <div class="uni-card" style="background: #fff">
            <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
              <a-form-model-item label="项目编号">
                <a-input v-model="filterForm.projectCode" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="项目名称">
                <a-input v-model="filterForm.projectName" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="保养标准">
                <a-input v-model="filterForm.maintainStandard" placeholder="请输入" />
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
        <div class="footer-submit">
          <a-button class="margin-btn" @click="resetFilter">重置</a-button>
          <a-button type="primary" @click="handleFilter">确定</a-button>
        </div>
      </div>
    </a-drawer>
    <!-- 新建编辑表单弹窗 -->
    <a-modal
      :title="formModel.title"
      :visible="formModel.visible"
      :confirm-loading="formModel.confirmLoading"
      @ok="submitForm"
      @cancel="cancelForm"
    >
      <a-form :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }" @submit="submitForm">
        <a-form-item>
          <span slot="label">项目编号：</span>
          <a-input
            :maxLength="16"
            v-decorator="[
              'projectCode',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入项目编号',
                  },
                  {
                    message: '该值不可用，系统中已存在！',
                    validator: (rule, value, callback) =>
                      validateDuplicateValue('mess_device_maintain_item', 'project_code', value, detailInfo.id, callback),
                  },
                ],
              },
            ]"
            placeholder="请输入"
            v-show="!isEdit"
          />
          <span class="btn-text code-btn" @click="genEntityCode" v-if="!isEdit">自动生成</span>
          <span v-else>{{ detailInfo.projectCode }}</span>
        </a-form-item>
        <a-form-item>
          <span slot="label">项目名称：</span>
          <a-input
            :maxLength="30"
            v-decorator="['projectName', { rules: [{ required: true, message: '请输入项目名称' }] }]"
            placeholder="请输入"
          />
        </a-form-item>
        <a-form-item>
          <span slot="label">保养标准：</span>
          <a-textarea
            placeholder="请输入"
            :maxLength="100"
            :auto-size="{ minRows: 2, maxRows: 6 }"
            v-decorator="['maintainStandard', { rules: [{ required: true, message: '请输入保养标准' }] }]"
          />
        </a-form-item>
        <div class="ant-form-item"></div>
      </a-form>
    </a-modal>
    <!-- 全选/分页 -->
    <div class="uni-card resetPadding" :style="{position: 'fixed', bottom:0,right:0,zIndex:2,left:collapsed?'79px':'208px', background: '#fff',paddingLeft:'43px'} ">
      <div style="display: inline-block">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span style="margin-left: 8px">
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
          <span class="btn-text" @click="clearArr" style="margin: 0 10px">清空</span>
          <span class="btn-text" @click="batchAction">删除</span>
        </span>
      </div>
      <div style="display: inline-block; float: right">
        <a-pagination
          :total="total"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :page-size="pageSize"
          @change="onChangePage"
          @showSizeChange="onShowSizeChange"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import crumbs from '@/components/crumbs.vue'
import { getNewColumns, subStrText, validateDuplicateValue } from '@/utils/util'
import { API } from '@/api/requestFzs'
import moment from 'dayjs'
import { mapState } from 'vuex'
import tableDragResize from '@/mixins/tableDragResize'
// 表头
const columnsValue = [
  {
    title: '项目编号',
    width: 250,
    ellipsis: true,
    dataIndex: 'projectCode',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'projectCode',
    },
  },
  {
    title: '项目名称',
    width: 120,
    ellipsis: true,
    dataIndex: 'projectName',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'projectName',
    },
  },
  {
    title: '保养标准',
    width: 200,
    ellipsis: true,
    dataIndex: 'maintainStandard',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'maintainStandard',
    },
  },
  {
    title: '创建时间',
    width: 150,
    ellipsis: true,
    dataIndex: 'createTime',
    scopedSlots: { customRender: 'createTime' },
  },
  {
    title: '创建人',
    width: 100,
    ellipsis: true,
    dataIndex: 'createByText',
  },
]
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    width: 100,
    dataIndex: 'actions',
    ellipsis: true,
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  mixins: [tableDragResize],
  data() {
    return {
      moment,
      validateDuplicateValue,
      subStrText,
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      showFilter: false, // 筛选抽屉
      modelList: [], // 列表数据
      selectedRowKeys: [], // 列表已选择数据
      showSetColumn: false, // 显示
      colunmArr: [
        {
          checkAll: false, //当前组是否全选
          indeterminate: false, //当前组不全选且有选择项时显示状态
          checkedList: [], //已选数据（不包括所有属性，只含有所选项的每一项的value）
          selectList: [], //已选数据（包括所有属性）
          topTitle: '基础字段', //当前组顶部字段
          plainOptions: [], //当前组提供可供选择的选项
        },
      ],
      //全选按钮
      indeterminate: false,
      checkAll: false,
      current: 1,
      total: 0,
      pageSize: 10,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      columns: [
        {
          title: '项目编号',
          width: 250,
          ellipsis: true,
          dataIndex: 'projectCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'projectCode',
          },
        },
        {
          title: '项目名称',
          width: 120,
          ellipsis: true,
          dataIndex: 'projectName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'projectName',
          },
        },
        {
          title: '保养标准',
          width: 200,
          ellipsis: true,
          dataIndex: 'maintainStandard',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'maintainStandard',
          },
        },
        {
          title: '创建时间',
          width: 150,
          ellipsis: true,
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' },
        },
        {
          title: '创建人',
          width: 100,
          ellipsis: true,
          dataIndex: 'createByText',
        },
        // {
        //   fixed: 'right',
        //   title: '操作',
        //   width: 100,
        //   dataIndex: 'actions',
        //   ellipsis: true,
        //   scopedSlots: { customRender: 'actions' },
        // },
      ],
      filterForm: {
        projectCode: '',
        projectName: '',
        maintainStandard: '',
      },
      filteredFormLable: {
        projectCode: '项目编号',
        projectName: '项目名称',
        maintainStandard: '保养标准',
      },
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
      formModel: {
        visible: false,
        title: '新建保养项目',
        confirmLoading: false,
      },
      form: this.$form.createForm(this, { name: 'coordinated' }),
      detailInfo: {},
      isEdit: false,
      tableKey: 1.9
    }
  },
  components: {
    SetColumn,
    crumbs,
  },
  computed: {
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        list.push({
          title: this.filteredFormLable[key],
          text: this.filterForm[key],
          key,
        })
      }
      return list
    },
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key] != '') {
          nums += 1
        }
      }
      return nums
    },
  },
  created() {
    this.initData()
    this.requestData()
  },
  mounted() {
    console.log('filteredNums:', this.filteredNums)
  },
  methods: {
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({entityCode: 'MESS_DEVICE_MAINTAIN_ITEM'}).then(res => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            projectCode: res.result
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    // 新建表单
    submitForm() {
      let submitApi = this.isEdit ? API.messDeviceMaintainItemEdit : API.messDeviceMaintainItemAdd
      this.form.validateFields((err, values) => {
        if (!err) {
          let parameter = {
            ...values
          }
          if (this.isEdit) {
            parameter.id = this.detailInfo.id
          }
          this.formModel.confirmLoading = true
          submitApi(parameter).then((res) => {
            if (res.code == 200) {
              this.formModel.confirmLoading = false
              this.$antdMessage.success(`${this.isEdit ? '编辑' : '新建'}成功！`)
              
              if (this.isEdit) {
                this.requestData()
              } else {
                this.handleSearch()
              }
              this.cancelForm()
            } else {
              this.formModel.confirmLoading = false
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
    // 取消新建
    cancelForm() {
      this.form.resetFields()
      this.isEdit = false
      this.formModel.visible = false
      this.detailInfo = {}
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {},
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)
        }
      } else {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            console.log('each != item.id:', each != item.id)
            return each != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.modelList) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        console.log('第一个参数是；', checkValue)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 批量删除
    batchAction() {
      let that = this
      if (that.selectedRowKeys.length > 0) {
        let ids = that.selectedRowKeys.join(',')
        API.messCheckItemCheckItem(ids).then((res) => {
          if (res.code == 200) {
            if (res.result) {
              this.batchDelete()
            } else {
              this.$warning({
                title: '该保养项目已被保养方案引用，无法删除',
              })
            }
          } else {
            this.$antdMessage.error(res.message)
          }
        })
      } else {
        that.$antdMessage.info('请先选择数据')
      }
    },
    batchDelete() {
      let that = this
      if (that.selectedRowKeys.length > 0) {
        let ids = that.selectedRowKeys.join(',')
        that.$antdConfirm({
          title: '请确定要删除吗?',
          content: `共选中${that.selectedRowKeys.length}条保养项目信息`,
          onOk() {
            console.log(ids)
            API.messDeviceMaintainItemDeleteBatch({ ids: ids }).then((res) => {
              if (res.code == 200) {
                that.$antdMessage.success('删除成功！')
                that.clearArr()
                that.handleSearch()
              } else {
                that.$antdMessage.error('该保养项目已被保养方案引用，无法删除')
              }
            })
          },
          onCancel() {},
        })
      } else {
        that.$antdMessage.info('请先选择数据')
      }
    },
    /* 清除 */
    clearArr() {
      this.selectedRowKeys = []
      this.checkBoxStatus()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    onShowSizeChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      this.filterForm[key] = ''
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        projectCode: '',
        projectName: '',
        maintainStandard: '',
      }
    },
    /* 初始/加载设置列 */
    initData() {
      var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.MAINTENANCE_ITEMS)
      this.columns = getNewColumns(columnsValue, JSON.parse(oldValue), actionArr, this.columns)
    },
    /* 请求列表数据 */
    requestData(check) {
      let parameter = {
        pageNo: this.current,
        pageSize: this.pageSize,
        ...this.filterForm,
        ...this.sortForm,
      }
      API.messDeviceMaintainItemList(parameter).then((res) => {
        if (res.code == 200) {
          if (res.result.total) {
            this.total = res.result.total
          } else {
            this.total = 0
          }
          this.modelList = res.result.records
          if (check) {
            this.checkBoxStatus()
          }
        }
      })
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(columnsValue, this.BUSI_CONST.Entity.MAINTENANCE_ITEMS, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      this.columns = getNewColumns(columnsValue, emitArr, actionArr, 150)
      console.log(this.columns)
      localStorage.setItem(this.BUSI_CONST.Entity.MAINTENANCE_ITEMS, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    /* 导入 */
    importFile() {},
    /* 导出 */
    exportFile() {},
    /* 新建 */
    handleAdd() {
      this.formModel.title = '新建保养项目'
      this.formModel.visible = true
    },
    /* 编辑 */
    handleEdit(v) {
      API.messDeviceMaintainItemQueryById({ id: v.id }).then(res => {
        if (res.result) {
          this.formModel.title = '编辑保养项目'
          this.formModel.visible = true
          this.isEdit = true
          this.detailInfo = res.result
          let formData = {
            projectCode: res.result.projectCode,
            projectName: res.result.projectName,
            maintainStandard: res.result.maintainStandard,
          }
          this.$nextTick(() => {
            this.form.setFieldsValue(formData)
          })
        }
      })
    },
    /* 删除 */
    handleDelete(v) {
      API.messCheckItemCheckItem(v.id).then((res) => {
          if (res.code == 200) {
            if (res.result) {
              this.handleToDelete(v)
            } else {
              this.$warning({
                title: '该保养项目已被保养方案引用，无法删除',
              })
            }
          } else {
            this.$antdMessage.error(res.message)
          }
        })
      // 先判断是否可删除，不可删除提示：该保养项目已被保养方案引用，无法删除，可删除则继续执行
    },
    handleToDelete(v) {
      let that = this
      that.$antdConfirm({
        title: '确定删除吗?',
        content: ``,
        onOk() {
          that.clearArr()
          API.messDeviceMaintainItemDelete({id: v.id}).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success('删除成功！')
              if (that.modelList.length === 1) {
                that.current = that.current == 1 ? 1 : that.current - 1
              }
              that.requestData()
            } else {
              that.$antdMessage.error('该保养项目已被保养方案引用，无法删除')
            }
          })
        },
        onCancel() {},
      })
    },
    //点击返回按钮
    goBack() {
      console.log('goback')
    },
    /* 列表选择 */
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
      this.checkBoxStatus()
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
.code-btn {
  position: absolute;
  right: 11px;
  top: -11px;
}
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.header {
  width: 150%;
  margin: -12px -12px @distance4;
}
.backBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .backC {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
.j-table-force-nowrap {
  margin-top: @distance1;
}
.btns {
  margin-left: @distance5;
}
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
}
.mg-left {
  margin-left: @distance3;
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}
.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
/deep/ .ant-card-body {
  height: calc(100vh - 214px);
  overflow: hidden;
  padding: 20px 16px;
}
</style>
